<?php

namespace app\controller\admin\genshinteam;

use app\model\api\GenshinRole;
use app\model\api\GenshinTeam;
use app\model\api\GenshinTeamRole;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Db;
use think\response\Json;

/**
 * Class Team
 * @package app\controller\admin\genshinteam
 */
class Team extends Backend
{
    /**
     *
     * @var GenshinTeam
     */
    protected $model;
    protected $hasSoftDel=0;//是否拥有软删除功能

    protected $noNeedLogin = []; // 无需登录即可请求的方法
    protected $noNeedAuth = ['index', 'info']; // 无需鉴权即可请求的方法

    public $orderRule = ['sort' => 'desc', 'id' => 'asc'];

    protected $position = [
        'top_main_',
        'top_vice_',
        'top_assist1_',
        'top_assist2_',
        'bottom_main_',
        'bottom_vice_',
        'bottom_assist1_',
        'bottom_assist2_',
    ];


    public function _initialize()
    {
        $this->model = new GenshinTeam();
    }


    //添加
    public function add()
    {
        Db::startTrans();
        try {
            $post     = $this->request->post();
            $roleInfo = (new GenshinRole())->roleInfo();

            $teamInfo = [
                'author_id' => $post['author_id'],
                'tag'       => $post['tag'],
                'team_name' => $post['team_name'],
                'team_desc' => $post['team_desc'],
                'cover'     => $roleInfo[$post['top_main_role_id']]['nation'],
                'keywords'  => json_encode(explode(',',$post['keywords']),JSON_UNESCAPED_UNICODE),
                'top_main_role_id' => $post['top_main_role_id'],
                'top_vice_role_id' => $post['top_vice_role_id'],
                'top_assist1_role_id' => $post['top_assist1_role_id'],
                'top_assist2_role_id' => $post['top_assist2_role_id'],
                'bottom_main_role_id' => $post['bottom_main_role_id'],
                'bottom_vice_role_id' => $post['bottom_vice_role_id'],
                'bottom_assist1_role_id' => $post['bottom_assist1_role_id'],
                'bottom_assist2_role_id' => $post['bottom_assist2_role_id'],
                'reaction' => json_encode(self::reaction(array(
                    $roleInfo[$post['top_main_role_id']]['element'],
                    $roleInfo[$post['top_vice_role_id']]['element'],
                    $roleInfo[$post['top_assist1_role_id']]['element'],
                    $roleInfo[$post['top_assist2_role_id']]['element'],
                )),JSON_UNESCAPED_UNICODE)
            ];

            if(!empty($post['bottom_main_role_id'])){
                $teamInfo['reaction_bottom'] = json_encode(self::reaction(array(
                    $roleInfo[$post['bottom_main_role_id']]['element'],
                    $roleInfo[$post['bottom_vice_role_id']]['element'],
                    $roleInfo[$post['bottom_assist1_role_id']]['element'],
                    $roleInfo[$post['bottom_assist2_role_id']]['element'],
                )),JSON_UNESCAPED_UNICODE);
            }

            $saveTeam    = $this->model->save($teamInfo);
            if (!$saveTeam) throw new \Exception('保存组队基本信息失败');

            $saveTeamRoleData = [];
            foreach($this->position as $prefix){
                if(!empty($post[$prefix.'role_id'])){
                    $type = 1;
                    if(str_contains($prefix.'role_id','bottom') !== false){
                        $type = 2;
                    }
                    $saveTeamRoleData[] = [
                        'type' => $type,
                        'team_id' => $this->model->id,
                        'position' => $post[$prefix.'role_pos'],
                        'role_id' => $post[$prefix.'role_id'],
                        'weapon_id' => $post[$prefix.'role_weapon'],
                        'artifact_id' => json_encode(explode(',',$post[$prefix.'role_relics'])),
                        'mainstats' => json_encode(explode(',',$post[$prefix.'role_tag']),JSON_UNESCAPED_UNICODE),
                        'substats' => json_encode(explode(',',$post[$prefix.'role_recommend']),JSON_UNESCAPED_UNICODE),
                    ];
                }
            }

            $roleModel     = new GenshinTeamRole();
            $saveAllMenu = $roleModel->saveAll($saveTeamRoleData);
            if (!$saveAllMenu) throw new \Exception('保存角色失败');

            Db::commit();
            $this->clearCache();
            return $this->success('操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->exceptionError($e);
        }
    }

    //编辑
    public function edit()
    {
        $id = $this->request->param('id');
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');

        Db::startTrans();
        try {
            $post     = $this->request->post();
            $roleInfo = (new GenshinRole())->roleInfo();

            $row->author_id = $post['author_id'];
            $row->tag       = $post['tag'];
            $row->team_name = $post['team_name'];
            $row->team_desc = $post['team_desc'];
            $row->cover     = $roleInfo[$post['top_main_role_id']]['nation'];
            $row->keywords  = json_encode(explode(',',$post['keywords']),JSON_UNESCAPED_UNICODE);
            $row->top_main_role_id = $post['top_main_role_id'];
            $row->top_vice_role_id = $post['top_vice_role_id'];
            $row->top_assist1_role_id = $post['top_assist1_role_id'];
            $row->top_assist2_role_id = $post['top_assist2_role_id'];
            $row->bottom_main_role_id = $post['bottom_main_role_id'];
            $row->bottom_vice_role_id = $post['bottom_vice_role_id'];
            $row->bottom_assist1_role_id = $post['bottom_assist1_role_id'];
            $row->bottom_assist2_role_id = $post['bottom_assist2_role_id'];
            $row->reaction  = json_encode(self::reaction(array(
                $roleInfo[$post['top_main_role_id']]['element'],
                $roleInfo[$post['top_vice_role_id']]['element'],
                $roleInfo[$post['top_assist1_role_id']]['element'],
                $roleInfo[$post['top_assist2_role_id']]['element'],
            )),JSON_UNESCAPED_UNICODE);

            if(!empty($post['bottom_main_role_id'])){
                $row->reaction_bottom = json_encode(self::reaction(array(
                    $roleInfo[$post['bottom_main_role_id']]['element'],
                    $roleInfo[$post['bottom_vice_role_id']]['element'],
                    $roleInfo[$post['bottom_assist1_role_id']]['element'],
                    $roleInfo[$post['bottom_assist2_role_id']]['element'],
                )),JSON_UNESCAPED_UNICODE);
            }


            $saveTeam = $row->save();
            if ($saveTeam === false) throw new \Exception('保存组队基本信息失败');

            $roleModel     = new GenshinTeamRole();
            $roleModel->where('team_id',$id)->delete();

            $saveTeamRoleData = [];
            foreach($this->position as $prefix){
                if(!empty($post[$prefix.'role_id'])){
                    $type = 1;
                    if(str_contains($prefix.'role_id','bottom') !== false){
                        $type = 2;
                    }
                    $saveTeamRoleData[] = [
                        'type' => $type,
                        'team_id' => $row['id'],
                        'position' => $post[$prefix.'role_pos'],
                        'role_id' => $post[$prefix.'role_id'],
                        'weapon_id' => $post[$prefix.'role_weapon'],
                        'artifact_id' => json_encode(explode(',',$post[$prefix.'role_relics'])),
                        'mainstats' => json_encode(explode(',',$post[$prefix.'role_tag']),JSON_UNESCAPED_UNICODE),
                        'substats' => json_encode(explode(',',$post[$prefix.'role_recommend']),JSON_UNESCAPED_UNICODE),
                    ];
                }
            }

            $saveAllMenu = $roleModel->saveAll($saveTeamRoleData);
            if (!$saveAllMenu) throw new \Exception('保存角色失败');

            Db::commit();
            $this->clearCache();
            return $this->success('操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }


    public function info(){
        $id = $this->request->param('id');

        $team = $this->model->where('id',$id)->find()->toArray();
        $returnData = array(
            'id' => $team['id'],
            'author_id' => $team['author_id'],
            'tag'       => $team['tag'],
            'team_name' => $team['team_name'],
            'team_desc' => $team['team_desc'],
            'keywords'  => self::jsonTransStr($team['keywords']),
            'top_main_role_id' => $team['top_main_role_id'],
            'top_vice_role_id' => $team['top_vice_role_id'],
            'top_assist1_role_id' => $team['top_assist1_role_id'],
            'top_assist2_role_id' => $team['top_assist2_role_id'],
            'bottom_main_role_id' => $team['bottom_main_role_id'],
            'bottom_vice_role_id' => $team['bottom_vice_role_id'],
            'bottom_assist1_role_id' => $team['bottom_assist1_role_id'],
            'bottom_assist2_role_id' => $team['bottom_assist2_role_id'],
            'reaction' => json_decode($team['reaction'],true),
            'reaction_bottom' => json_decode($team['reaction_bottom'],true)
        );
        $teamRole = (new GenshinTeamRole())->where(array('team_id' => $id))->column('position,weapon_id,artifact_id,mainstats,substats','role_id');
        foreach($this->position as $item){
            if(!empty($returnData[$item.'role_id'])){
                $returnData[$item.'role_pos'] = $teamRole[$returnData[$item.'role_id']]['position'];
                $returnData[$item.'role_weapon'] = $teamRole[$returnData[$item.'role_id']]['weapon_id'];
                $returnData[$item.'role_relics'] = $this->jsonTransStr($teamRole[$returnData[$item.'role_id']]['artifact_id']);
                $returnData[$item.'role_tag'] = $this->jsonTransStr($teamRole[$returnData[$item.'role_id']]['mainstats']);
                $returnData[$item.'role_recommend'] = $this->jsonTransStr($teamRole[$returnData[$item.'role_id']]['substats']);
            }
        }

        return $this->success('获取成功', $returnData);
    }

    public $all_reaction = array(
        'all'   => array(
            'title'   => '【交织之护】',
            'content' => '所有元素抗性提升15%，物理抗性提升15%'
        ),
        'pyro'  => array(
            'title'   => '【热诚之火】',
            'content' => '冰元素附着的持续时间下降40%。攻击力提高25%'
        ),
        'anemo' => array(
            'title'   => '【迅捷之风】',
            'content' => '体力消耗降低15%，移动速度提升10%，技能冷却时间缩短5%'
        ),
        'geo'   => array(
            'title'   => '【坚定之岩】',
            'content' => '护盾强效提升15%。此外，角色处于护盾庇护下时，具有如下特性：造成的伤害提升15%；角色对敌人造成伤害时，会使敌人的岩元素抗性降低20%，持续15秒'
        ),
        'electro' => array(
            'title'   => '【强能之雷】',
            'content' => '水元素附着持续时间下降40%。触发超导、超载和感电反应时，有100%概率掉落1个雷元素微粒，冷却时间5秒'
        ),
        'hydro'   => array(
            'title'   => '【愈疗之水】',
            'content' => '火元素附着的持续时间下降40%。受治疗效果提升30%'
        ),
        'cryo'    => array(
            'title'   => '【粉碎之冰】',
            'content' => '雷元素附着持续时间下降40%。攻击冰元素附着或冻结状态下的敌人时，暴击率提高15%'
        ),
    );


    /**
     * 元素共鸣分析
     * @param $element
     * @return array
     */
    public function reaction($element){
        $reaction = [];
        $new_element = array_unique($element);
        if(count($element) == count($new_element)){
            $reaction[] = array(
                'name' => $this->all_reaction['all']['title'],
                'element' =>$element,
                'description' => $this->all_reaction['all']['content']
            );
        }else{
            $new1_element = array_diff_assoc($element,$new_element);
            foreach($new1_element as $ele){
                if(!empty($this->all_reaction[$ele])){
                    $reaction[$this->all_reaction[$ele]['title']] = array(
                        'name' => $this->all_reaction[$ele]['title'],
                        'element' =>[$ele,$ele],
                        'description' => $this->all_reaction[$ele]['content']
                    );
                }
            }
        }
        return array_values($reaction);
    }


    /**
     * 词条
     * @return false|string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function tag(){
        return $this->success('数据获取成功', array(
            ['name' => '攻击力百分比'],
            ['name' => '冰元素伤害加成'],
            ['name' =>'暴击伤害'],
            ['name' =>'元素充能效率'],
            ['name' =>'暴击率'],
            ['name' =>'生命值百分比'],
            ['name' =>'治疗加成'],
            ['name' =>'火元素伤害加成'],
            ['name' =>'元素精通'],
            ['name' =>'风元素伤害加成'],
            ['name' =>'水元素伤害加成'],
            ['name' =>'岩元素伤害加成'],
            ['name' =>'防御力百分比'],
        ));
    }


    /**
     * @param $str
     * @return string
     */
    public function jsonTransStr($str){
        if(empty($str)){
            return '';
        }
        $json = json_decode($str,true);
        return implode(',',$json);
    }
}